<template>
  <div
    class="head-container"
    v-if="status == 0"
    style="display: flex; justify-content: center; padding-bottom: 8px"
  >
    <div>
      <el-button type="primary" plain @click="openForm('create')">新增项目</el-button>
    </div>
  </div>
  <div class="head-container">
    <el-input v-model="deptName" class="mb-20px" clearable placeholder="请输入项目名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>

  <div
    class="head-container"
    v-if="status == 0"
    style="display: flex; justify-content: center; padding-bottom: 8px"
  >
    <div>
      <el-button
        :disabled="checkedId.length == 0"
        type="primary"
        size="small"
        @click="editForm('update')"
        >编辑
      </el-button>
      <el-button
        :disabled="checkedId.length == 0"
        type="danger"
        size="small"
        @click="removeProject()"
        >删除
      </el-button>
    </div>
  </div>

  <div class="head-container">
    <el-tree
      ref="treeRef"
      :data="projectList"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :props="defaultProps"
      default-expand-all
      highlight-current
      node-key="id"
      show-checkbox
      @node-click="handleNodeClick"
      @check-change="handleCheckChange"
    >
      <template v-if="status == 0" #default="{ node }">
        <span>{{ node.label }}</span>
      </template>
    </el-tree>
  </div>

  <!-- 表单弹窗：添加/修改 -->
  <ProjectForm ref="formRef" @success="getTree" />
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import { ProjectApi } from '@/api/task/project/index.js'
import { defaultProps, handleTree } from '@/utils/tree'
import ProjectForm from './ProjectForm.vue'

const props = defineProps({
  refresh: {
    type: Boolean,
    required: false
  }
})
/** 监听是否需要刷新 */
watch(
  () => props.refresh,
  (newVal, oldVal) => {
    console.log('refresh', newVal)
    if (newVal) {
      getTree()
    }
  }
)
const message = useMessage() // 消息弹窗
defineOptions({ name: 'ProjectTree' })
const { currentRoute } = useRouter()
const deptName = ref('')
const { t } = useI18n() // 国际化
const projectList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()
const status = currentRoute.value.meta.query.status ? currentRoute.value.meta.query.status : 0
/** 获得部门树 */
const getTree = async () => {
  let params = {
    status: status
  }
  const res = await ProjectApi.getProjectList(params)
  projectList.value = []
  projectList.value.push(...handleTree(res))
  emits('node-click', projectList.value[0])
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const checkedId = ref([])
//编辑项目名称
const editForm = async (type) => {
  formRef.value.open(type, checkedId.value[0])
  await getTree()
}

const remove = async (id) => {
  await ProjectApi.deleteProject(id)
  await getTree()
  message.success(t('common.delSuccess'))
}
//删除项目
const removeProject = () => {
  remove(checkedId.value[0])
}

const handleCheckChange = (data, checked, indeterminate) => {
  // 获取所有已选中的节点
  const checkedKeys = treeRef.value.getCheckedKeys()
  console.log('checkedKeys', checkedKeys)
  checkedId.value = checkedKeys
  console.log('checkedId', checkedId.value)
  console.log('checkedId', checkedId.value.length)
  // 如果当前有其他节点选中，移除它们的选中状态
  if (checkedKeys.length > 1) {
    const otherCheckedKeys = checkedKeys.filter((key) => key !== data.id)
    treeRef.value.setCheckedKeys([data.id])
    otherCheckedKeys.forEach((key) => {
      treeRef.value.setChecked(key, false)
    })
    treeRef.value.setChecked(data.id, checked)
  }
}

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 处理项目被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {
  emits('node-click', row)
}
const emits = defineEmits(['node-click'])

/** 监听deptName */
watch(deptName, (val) => {
  treeRef.value!.filter(val)
})



/** 初始化 */
onMounted(async () => {
  await getTree()
})
</script>
<style scoped lang="scss">
.custom-tree-node {
  //flex: 1;
  //display: flex;
  //
  //white-space: normal;
  //align-items: center;
  //justify-content: space-between;
  //font-size: 14px;
  //padding-right: 8px;
}

:deep(.el-tree-node) {
  white-space: normal;
  word-wrap: break-word;
  overflow-wrap: break-word;
  word-break: break-all;
  outline: 0;

  .el-tree-node__content {
    text-align: left;
    align-items: start;
    margin: 4px;
    height: 100%;
  }
}
</style>
